<?php

class ProfileController extends Controller {

    public function actionIndex() {
        $this->ui->addScript('profile', ClientScript::profileScript());
//        $model = $this->current_user->userProfile;
        $model = UserProfile::model()->find('user_id = :user_id', array(':user_id' => $this->current_user->id));
        if (!is_object($model)) {
            $model = new UserProfile();
            $model->user_id = yii::app()->user->getId();
        }
        $this->ajaxValidate($model);
        $old_name_avatar = $model->avatar;
        if (Yii::app()->request->isPostRequest) {
            $model->attributes = $_POST['UserProfile'];
            $uploadedFile = CUploadedFile::getInstance($model, 'avatar');
            $str_ran = 'profile_' . generateRandomString(10) . '_' . time() . '.' . pathinfo($uploadedFile, PATHINFO_EXTENSION);
            $model->avatar = $str_ran;
            if ($model->validate()) {
                if ($model->save()) {
                    if (is_object($uploadedFile)) {
                        $uploadedFile->saveAs(Yii::app()->basePath . '/../upload/' . $str_ran);
                        if(!empty($old_name_avatar) && file_exists(Yii::app()->basePath . '/../upload/' . $old_name_avatar)) {
                            unlink(Yii::app()->basePath . '/../upload/' . $old_name_avatar);
                        }
                    }
                }
                Yii::app()->user->setFlash('success', Yii::t('main', 'Cập nhật thành công!'));
                $this->redirect(Yii::app()->createUrl('users/profile'));                
            }
        }

        $this->render('index', array(
            'model' => $model
        ));
    }

}